package com.tsingteng.cosfun;

import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;


import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.bean.OpusBean;
import com.tsingteng.cosfun.bean.CommBackBean;
import com.tsingteng.cosfun.bean.ReportBean;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.ActivityManagers;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.http.Url;
import com.tsingteng.cosfun.ui.cosfun.CosFragmentNew;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverListener;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverManager;
import com.tsingteng.cosfun.ui.costar.CostarFragment;
import com.tsingteng.cosfun.ui.focus.FocusFragment;
import com.tsingteng.cosfun.ui.found.FoundFragment;
import com.tsingteng.cosfun.ui.login.report.ReportContract;
import com.tsingteng.cosfun.ui.login.report.ReportPresenter;
import com.tsingteng.cosfun.ui.message.CommonActivity;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.NotchUtil;
import com.tsingteng.cosfun.utils.StringUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.widget.ButtomView;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;


/**
 * 描述: 住页面
 * 创建人: 肖利
 * 时间: 2018/7/30
 * qq: (872179966)
 */
public class MainActivity extends AppCompatActivity implements ButtomView.OnSelectBottomListener, ReportContract.IReportView {
    String TAG = MainActivity.class.getSimpleName();
    private ButtomView mBv;
    private int currentPosition = -1;
    private boolean isPress = false;

    private Fragment mCosfunFragment;
    private Fragment mFocusFragment;
    private Fragment mCostarFragment;
    private Fragment mFoundFragment;
    private Fragment mMineFragment;

    private List<Fragment> fragmentList = new ArrayList<>();

    //摇一摇
    private SensorManager sensorManager;
    private Sensor sensor;
    private Vibrator vibrator;
    private static final int UPTATE_INTERVAL_TIME = 50;
    private static final int SPEED_SHRESHOLD = 30;//这个值调节灵敏度
    private long lastUpdateTime;
    private float lastX;
    private float lastY;
    private float lastZ;
    public boolean isFull = false;
    private int type = 0;
    private boolean isFound = false;
    private AudioManager audio = null;
    private ReportPresenter reportPresenter;
    private List<Fragment> listFrag=new ArrayList<>();
    private int count;
    private String mNewFocused;
    private boolean mCosFra = true;
    private boolean mFocusFra = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityManagers.getInstance().addActivity(this);
        Intent intent = getIntent();
        type = intent.getIntExtra("type", 0);
        NotchUtil.setWindowTrans(this, true, false);
        initView();
    }


    protected void initView() {
        reportPresenter = new ReportPresenter(this);
        mBv = (ButtomView) findViewById(R.id.bv_button);
        mBv.setOnSelectBottomListener(this);
        count = VideoHelper.getIntence().getNotRead();
        if (0 != count) {
            mBv.setVisible();
            String mCount;
            if (count > 99) {
                mCount = "99";
            } else {
                mCount = String.valueOf(count);
            }
            mBv.setReadCount(mCount);
        } else {
            mBv.setGone();
        }
        initFragment();
//        requestPermission();

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);


        if (sensorManager != null) {
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
        audio = (AudioManager) this.getSystemService(Service.AUDIO_SERVICE);
    }

    private void initFragment() {
        if (mCosfunFragment == null) mCosfunFragment = new CosFragmentNew();
        if (mFocusFragment == null) mFocusFragment = new FocusFragment();
        if (mCostarFragment == null) mCostarFragment = new CostarFragment();
        if (mFoundFragment == null) mFoundFragment = new FoundFragment();
        if (mMineFragment == null) mMineFragment = new HomeMineFragment();
        ((HomeMineFragment) mMineFragment).setIsChange(false);
        ((HomeMineFragment) mMineFragment).setCurrentPosition(4);
        fragmentList.add(mCosfunFragment);
        fragmentList.add(mFocusFragment);
        fragmentList.add(mCostarFragment);
        fragmentList.add(mFoundFragment);
        fragmentList.add(mMineFragment);

        chageFragment(type==2?0:type, currentPosition, fragmentList);
        currentPosition = type;
        mBv.setButtomUI(type);
        String mNotificationType = getIntent().getStringExtra(Constant.NOTIFICATION);
        if (!TextUtils.isEmpty(mNotificationType)){
            clickNotification(mNotificationType);
        }
    }

    //处理摇一摇
    private void handleShark() {
        if (currentPosition == 0) {
            if (fragmentList.get(0) instanceof CosFragmentNew) {
                ((CosFragmentNew) fragmentList.get(0)).shark();
            }
        } else if (currentPosition == 1) {
            if (fragmentList.get(1) instanceof FocusFragment) {
                ((FocusFragment) fragmentList.get(1)).shark();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //回到首页之后直接跳到首页
        AppListener.getInstance().setOnToMainActivityListener(new AppListener.OnToMainActivityListener() {
            @Override
            public void OnVideoToMain() {
                type=0;
                LogUtils.e("0000000000000","回到首页之后直接跳到首页");
                chageFragment(type, currentPosition, fragmentList);
                currentPosition = type;
                mBv.setButtomUI(type);
            }
        });
        AppListener.getInstance().setOnToFoundActivityListeners(new AppListener.OnToFoundActivityListeners() {
            @Override
            public void OnVideoToFound() {
                long activityId;
                OpusBean mOpusBean = VideoHelper.getIntence().getmOpusBean();
                if (null ==mOpusBean){
                    JoinCostarBean joinCostarBean = VideoHelper.getIntence().getmJoinCostarBean();
                    activityId = joinCostarBean.getActivityId();
                }else{
                    activityId = mOpusBean.getActivityId();
                }
                type=3;
                chageFragment(type, currentPosition, fragmentList);
                currentPosition = type;
                mBv.setButtomUI(type);
                Navigate.gotoActivityDetail(MainActivity.this, Url.ACTIVITY_URL,activityId);
            }
        });
        AppListener.getInstance().setOnAttentFocusBackListener(new AppListener.OnAttentFocusBackListener() {
            @Override
            public void onAttentBack() {
                mNewFocused = Constant.FOCUSED;
            }
        });
        if (sensor != null) {
            sensorManager.registerListener(sensorEventListener,
                    sensor,
                    SensorManager.SENSOR_DELAY_GAME);//这里选择感应频率
        }
        if (currentPosition == 0) {
            if (fragmentList.get(0) instanceof CosFragmentNew) {
                ((CosFragmentNew) fragmentList.get(0)).play();
            }
        } else if (currentPosition == 1) {
            if (fragmentList.get(1) instanceof FocusFragment) {
                ((FocusFragment) fragmentList.get(1)).play();
            }
        } else {
            if (fragmentList.get(0) instanceof CosFragmentNew) {
                ((CosFragmentNew) fragmentList.get(0)).onPause();
            }
            if (fragmentList.get(1) instanceof FocusFragment) {
                ((FocusFragment) fragmentList.get(1)).onPause();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (fragmentList.get(0) instanceof CosFragmentNew) {
            ((CosFragmentNew) fragmentList.get(0)).onPause();
        }
        if (fragmentList.get(1) instanceof FocusFragment) {
            ((FocusFragment) fragmentList.get(1)).onPause();
        }
        if (sensorManager != null) {
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    @Override
    public void onSelectHome() {
        AppUtils.setToLogonActivity(false);
        AppUtils.setIsShowNetDialog(true);
//        HomeMineFragment.isNeedFresh = true;
        isFull = true;
        mCosFra = true;
        mFocusFra = false;
        chageFragment(0, currentPosition, fragmentList);
        currentPosition = 0;
        if (fragmentList.get(0) instanceof CosFragmentNew) {
            ((CosFragmentNew) fragmentList.get(0)).play();
        }
        if (fragmentList.get(1) instanceof FocusFragment) {
            ((FocusFragment) fragmentList.get(1)).onPause();
        }
        foundGone();
        if (!TextUtils.isEmpty(mNewFocused)) {
            focusBack();
            mNewFocused = "";
        }
    }

    @Override
    public boolean onSelectAtt() {
        AppUtils.setToLogonActivity(true);
        AppUtils.setIsShowNetDialog(true);
        isFull = true;
        mCosFra = false;
        mFocusFra = true;
        if (fragmentList.get(0) instanceof CosFragmentNew) {
            ((CosFragmentNew) fragmentList.get(0)).onPause();
        }
        if (fragmentList.get(1) instanceof FocusFragment) {
            ((FocusFragment) fragmentList.get(1)).play();
        }
        if (LogonUtils.chckLogon(this, true, 1)) {
            chageFragment(1, currentPosition, fragmentList);
            foundGone();
            currentPosition = 1;
            if (!TextUtils.isEmpty(mNewFocused)) {
                focusBack();
                mNewFocused = "";
            }
            return true;
        }
        return false;
    }
   void focusBack(){
       AppListener.OnFocusOpusBackListener listener = AppListener.getInstance().getOnFocusOpuslistener();
       if (null !=listener){
           listener.onFocusOpusBack();
       }
   }

    @Override
    public void onSelectAdd() {
        isFull = false;
        mCosFra = true;
        mFocusFra = false;
        AppUtils.setToLogonActivity(true);
        AppUtils.setIsShowNetDialog(false);
        VideoHelper.getIntence().setActivityId(-1);
//        HomeMineFragment.isNeedFresh = true;
        if (fragmentList.get(0) instanceof CosFragmentNew) {
            ((CosFragmentNew) fragmentList.get(0)).onPause();
        }
        if (fragmentList.get(1) instanceof FocusFragment) {
            ((FocusFragment) fragmentList.get(1)).onPause();
        }
        if (LogonUtils.chckLogon(this, true, 2)) {
            foundGone();
            VideoHelper.getIntence().starVideoShoot(this);
            VideoHelper.getIntence().setActivityId(-1);
            if (!TextUtils.isEmpty(mNewFocused)) {
                focusBack();
                mNewFocused = "";
            }
        }

    }

    @Override
    public boolean onSelectMessage() {
        isFull = false;
        AppUtils.setIsShowNetDialog(false);
        mCosFra = true;
        mFocusFra = false;
        AppUtils.setToLogonActivity(true);
        if (fragmentList.get(0) instanceof CosFragmentNew) {
            ((CosFragmentNew) fragmentList.get(0)).onPause();
        }
        if (fragmentList.get(1) instanceof FocusFragment) {
            ((FocusFragment) fragmentList.get(1)).onPause();
        }
        isFound = true;
        chageFragment(3, currentPosition, fragmentList);
        currentPosition = 3;
        if (!TextUtils.isEmpty(mNewFocused)) {
            focusBack();
            mNewFocused = "";
        }
        return true;

    }

    @Override
    public boolean onSelectMine() {
        AppUtils.setToLogonActivity(true);
        AppUtils.setIsShowNetDialog(false);
        isFull = false;
        mCosFra = true;
        mFocusFra = false;
        if (fragmentList.get(0) instanceof CosFragmentNew) {
            ((CosFragmentNew) fragmentList.get(0)).onPause();
        }
        if (fragmentList.get(1) instanceof FocusFragment) {
            ((FocusFragment) fragmentList.get(1)).onPause();
        }
        if (LogonUtils.chckLogon(this, true, 4)) {
            chageFragment(4, currentPosition, fragmentList);
            foundGone();
            currentPosition = 4;
            if (!TextUtils.isEmpty(mNewFocused)) {
                focusBack();
                mNewFocused = "";
            }
            return true;
        }
        return false;

    }

    /**
     * 切换fragment
     *
     * @param position
     * @param currentPosition
     * @param fragmentList
     */
    protected void chageFragment(int position, int currentPosition, List<Fragment> fragmentList) {
        if (currentPosition == position) return;
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        if (currentPosition != -1)
            fragmentTransaction.hide(fragmentList.get(currentPosition));
        if (!fragmentList.get(position).isAdded()) {
            fragmentTransaction.add(R.id.contentContainer, fragmentList.get(position));
        } else {
//            if (fragmentList.get(position) instanceof HomeMineFragment) {
//                ((HomeMineFragment) fragmentList.get(position)).refreshData();
//            }
        }
        fragmentTransaction.show(fragmentList.get(position)).commitAllowingStateLoss();

    }

    @Override
    public void onBackPressed() {
        //个人主页需要点击物理返回键执行滑动返回
        if (currentPosition == 0 || currentPosition == 1) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            List<Fragment> fragmentList = fragmentManager.getFragments();
            if (fragmentList != null && fragmentList.size() > 0 && 0 == listFrag.size()) {
                listFrag.addAll(fragmentList);
            }
            for (int i = 0; i < listFrag.size(); i++) {
                Fragment fragment = listFrag.get(i);
                if (fragment instanceof HomeMineFragment) {
                    HomeMineFragment homeMineFragment = ((HomeMineFragment) fragment);
                    if (homeMineFragment.getNeedSmooth() && homeMineFragment.isVisible() &&
                            homeMineFragment.getCurrentPosition() == currentPosition) {
                        homeMineFragment.onBack();
                        listFrag.remove(fragment);
                        return;
                    }
                }
            }
        }
        //二次点击退出
        if (null ==fragmentList){
            return;
        }
        if (mCosFra) {
            CosFragmentNew mCosFragmentNew = ((CosFragmentNew) (fragmentList.get(0)));
            if (null == mCosFragmentNew || null == mCosFragmentNew.mFragmentPair) {
                twoClickFinish();
                return;
            }
            if (null == mCosFragmentNew.mFragmentPair.get(1).second) {
                return;
            }
            HomeMineFragment homeMineFragment = (HomeMineFragment) (mCosFragmentNew.mFragmentPair.get(1).second);
            assert homeMineFragment != null;
            if (!homeMineFragment.getUserVisibleHint()) {
                twoClickFinish();
            } else {
                homeMineFragment.onBack();
            }
        }else{
            FocusFragment mFocuFragment = (FocusFragment) (fragmentList.get(1));
            HomeMineFragment homeMineFragment1 = (HomeMineFragment) (mFocuFragment.mFragmentPair.get(1).second);
            assert homeMineFragment1 != null;
            if (!homeMineFragment1.getUserVisibleHint()){
                twoClickFinish();
            }else{
                homeMineFragment1.onBack();
            }
        }

    }

    /**
     * //二次点击退出
     */
    private void twoClickFinish() {
        if (isPress) {
            finish();
            ActivityManagers.getInstance().finishAllActivity();
        } else {
            isPress = !isPress;
            ToastUtils.showToast("再次点击退出应用");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isPress = false;
                }
            }, 2000);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    public void goHomeFragment() {
        if (mBv != null) {
            mBv.goHomeFocus();
        }
        chageFragment(0, currentPosition, fragmentList);
        currentPosition = 0;

    }
    public void goMainFragment() {
        if (null != mBv){
            mBv.goMainFocus();
        }
        chageFragment(0, currentPosition, fragmentList);
        currentPosition = 0;

    }

    long lastSharkTime = 0;// 上一次摇一摇时间
    int sharkCount = 0;// 震动次数
    /**
     * 重力感应监听
     */
    private SensorEventListener sensorEventListener = new SensorEventListener() {


        @Override
        public void onSensorChanged(SensorEvent event) {
            long currentUpdateTime = System.currentTimeMillis();
            long timeInterval = currentUpdateTime - lastUpdateTime;
            if (timeInterval < UPTATE_INTERVAL_TIME) {
                return;
            }
            lastUpdateTime = currentUpdateTime;
            // 传感器信息改变时执行该方法
            float[] values = event.values;
            float x = values[0]; // x轴方向的重力加速度，向右为正
            float y = values[1]; // y轴方向的重力加速度，向前为正
            float z = values[2]; // z轴方向的重力加速度，向上为正
            float deltaX = x - lastX;
            float deltaY = y - lastY;
            float deltaZ = z - lastZ;


            lastX = x;
            lastY = y;
            lastZ = z;
            double speed = (Math.sqrt(deltaX * deltaX + deltaY * deltaY
                    + deltaZ * deltaZ) / timeInterval) * 100;
            if (speed >= SPEED_SHRESHOLD) {
                sharkCount++;
                if (sharkCount > 10) {
                    handleShark();
                    lastSharkTime = System.currentTimeMillis();
                    sharkCount = 0;
                    vibrator.vibrate(300);
                }
            }
        }


        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                Log.e("--volume", "----- KEYCODE_VOLUME_UP");
                audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);

                ObserverManager.getInstance().notifyObserver(ObserverListener.KEYCODE_VOLUME_UP, 0, 0);

                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                Log.e("--volume", "----- KEYCODE_VOLUME_DOWN");
                audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
                ObserverManager.getInstance().notifyObserver(ObserverListener.KEYCODE_VOLUME_DOWN, 0, 0);

                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 下方tab显示与隐藏
     *
     * @param vibButtomView
     */
    public void setVibButtomView(int vibButtomView) {
        if (mBv != null) {
            mBv.setVisibility(vibButtomView);
        }
    }

    @Override
    public void showReportData(ReportBean data) {

    }

    @Override
    public void showReadCount(ReportBean data) {

    }

    void foundGone() {
        if (isFound) {
            mBv.setGone();
            if (0 != count) {
                reportPresenter.getReadAll();
            }
        }
    }

    @Override
    public void showReadAll() {
        count = 0;
    }

    @Override
    public void showFollowCount(CommBackBean commBackBean) {

    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    void clickNotification(String type){
        Intent clickIntent = new Intent();
        clickIntent.setClass(this, CommonActivity.class);
        if ("POINT".equals(type)) {
            //@我
            clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_AT_ME);
            clickIntent.putExtra("funType", "POINT");
            clickIntent.putExtra("biao", 2);
        } else if ("REVIEW".equals(type)) {
            //评论我
            clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_COMMENT);
            clickIntent.putExtra("funType", "REVIEW");
            clickIntent.putExtra("biao", 1);
        } else if ("FAVOR".equals(type)) {
            //赞我
            clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_GREAT);
            clickIntent.putExtra("funType", "FAVOR");
            clickIntent.putExtra("biao", 0);
        } else if ("FANS".equals(type)) {
            //粉丝
            clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_FANS);
            clickIntent.putExtra("funType", "FANS");
        } else if ("NOTICE".equals(type)) {
            //系统通知
            clickIntent.putExtra("CommonActivity.FRAGMENT_KEY", CommonActivity.KEY_JUMP_SYSTEM);

        } else if ("HELPER".equals(type)) {
            //官方助手
            clickIntent.putExtra("CommonActivity.FRAGMENT_KEY", CommonActivity.KEY_JUMP_OFFICAL);
        } else {
            clickIntent.putExtra("CommonActivity.FRAGMENT_KEY", CommonActivity.KEY_JUMP_SYSTEM);
        }
        startActivity(clickIntent);
    }
}
